﻿using QxFramework.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace QxFramework.Core
{
    /// <summary>
    /// 所有UI父对象的基类。
    /// </summary>
    public abstract class UIBase : MonoBehaviour
    {
        //用于存储和快速查找子物体
        public Dictionary<string, GameObject> _gos;

        /// <summary>
        /// 当UI被显示时执行。
        /// </summary>
        public virtual void OnDisplay(object args)
        {

        }

        /// <summary>
        /// 当注册消息处理方法时执行。
        /// </summary>
        public virtual void OnRegisterHandler()
        {
        }

        /// <summary>
        /// 当关闭时执行。
        /// </summary>
        public virtual void OnClose()
        {
            //TODO 考虑改成隐藏
            Destroy(gameObject);
            //if (gameObject!=null)
            //{
            //    ObjectPool.Recycle(gameObject);
            //}
            //else
            //{
            //    Debug.Log("Destroyed gameObject" + name);
            //}
        }

        /// <summary>
        /// 建立一个包含所有子物体的字典
        /// </summary>
        public void CollectObject()
        {
            //获取所有子物体
            _gos = new Dictionary<string, GameObject>();
            var childs = transform.GetComponentsInChildren<Transform>(true);//包括隐藏物体

            foreach (Transform child in childs)
            {
                _gos[child.name] = child.gameObject;
            }
        }

        /// <summary>
        /// 一个快速获取的函组件数，以物体名为Key，相同值则直接覆盖
        /// </summary>
        /// <typeparam name="T">组件</typeparam>
        /// <param name="name">物体名。</param>
        /// <returns>组件对象</returns>
        /// <exception cref="System.ArgumentNullException">没找到组件。</exception>
        public T Get<T>(string name)
        {
            if (_gos == null || !_gos.ContainsKey(name))
            {
                CollectObject();
            }
            if (!_gos.ContainsKey(name))
            {
                throw new ArgumentNullException(name);
            }

            return _gos[name].GetComponent<T>();
        }

        /// <summary>
        /// 清除字典里的值
        /// </summary>
        public void ClearDictionary()
        {
            _gos.Clear();
        }
    }
}